<?php

namespace app\cps\service;

use app\model\CustomRechargeTemplate;
use app\model\Link;
use app\model\ResponsibilityPerson;
use app\model\RechargeLimitTemplateCompany;
use app\model\RechargeLimitTemplateVideo;
use app\model\RechargeLimitTemplate;
use app\model\OfficialAccounts;
use app\model\Videos;
use app\common\Error;
use app\model\VideoDetails;

class CustomRechargeService
{
    private $model;
    private $linkModel;
    private $responsibilityPersonModel;
    private $rechargeLimitTemplateCompanyModel;
    private $rechargeLimitTemplateVideoModel;
    private $rechargeLimitTemplateModel;
    private $videosModel;
    private $videoDetailsModel;
    private $officialAccountsModel;

    public function __construct(CustomRechargeTemplate $model, Link $linkModel, ResponsibilityPerson $responsibilityPersonModel, RechargeLimitTemplateCompany $rechargeLimitTemplateCompanyModel, RechargeLimitTemplateVideo $rechargeLimitTemplateVideoModel, RechargeLimitTemplate $rechargeLimitTemplateModel, Videos $videosModel, VideoDetails $videoDetailsModel, OfficialAccounts $officialAccountsModel)
    {
        $this->model = $model;
        $this->linkModel = $linkModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
        $this->rechargeLimitTemplateCompanyModel = $rechargeLimitTemplateCompanyModel;
        $this->rechargeLimitTemplateVideoModel = $rechargeLimitTemplateVideoModel;
        $this->rechargeLimitTemplateModel = $rechargeLimitTemplateModel;
        $this->videosModel = $videosModel;
        $this->videoDetailsModel = $videoDetailsModel;
        $this->officialAccountsModel = $officialAccountsModel;
    }

    // 新增自定义充值模板
    public function addCustomRechargeTemplate($params, $userInfo)
    {
        $appletData = $this->officialAccountsModel->getInfoById($userInfo['cps_used_official_account_id'], 'applet_id');
        $params['responsibility_person_id'] = $userInfo['cps_user_id'];
        $params['applet_id'] = $appletData['applet_id'];
        $params['created_at'] = time();
        return $this->model->edit($params);
    }
    //删除自定义充值模板
    public function deleteCustomRechargeTemplate($params, $userInfo)
    {
        //当删除时，需要判断是否绑定推广链接，如果绑定就不能删除
        $linklist = $this->linkModel->getInfoByWhere(['recharge_template_id' => $params['id'],'is_new_back_setting'=>2], 'id,video_id');
        if(!empty($linklist)) {
            return ['message' => Error::VIDEO_NOT_DEILETE_BOUND_PROMOTION_LINK];
        }
        $params['status']=2;
        $params['updated_at'] = time();
        return $this->model->edit($params);
    }
    // 编辑自定义充值模板
    public function editCustomRechargeTemplate($params, $userInfo)
    {
        $params['updated_at'] = time();

        $info = $this->model->getInfoById($params['id'], 'id, video_id');
        // 加一个判断时因为原来的推广链接和现在的有冲突，所以用新自定义先判断是否为当前剧名
        if ($info['video_id'] != $params['video_id']) {
            $linkList = $this->linkModel->getInfoByWhere(['recharge_template_id' => $params['id'],'is_new_back_setting'=>2], 'id, video_id');

            if (!empty($linkList)) {
                return ['message' => Error::VIDEO_NOT_EDIT_BOUND_PROMOTION_LINK];
            }
        }
        $companyData = $this->responsibilityPersonModel->getInfoById($userInfo['cps_user_id'], 'company_id');

        $rechargeLimitTemplateVideoData = $this->rechargeLimitTemplateVideoModel->selectWithTemplateFirstByVideoId(['recharge_limit_template_id'], $params['video_id']);

        $bool = false;
        if ($rechargeLimitTemplateVideoData) {
            $rechargeLimitTemplateId = $rechargeLimitTemplateVideoData['recharge_limit_template_id'];
            $rechargeLimitTemplateCompanyData = $this->rechargeLimitTemplateCompanyModel->getDataByWhere(['recharge_limit_template_id' => $rechargeLimitTemplateId], 'company_id');

            if ($rechargeLimitTemplateCompanyData) {
                foreach ($rechargeLimitTemplateCompanyData as $key => $value) {
                    if ($value['company_id'] == $companyData['company_id']) {
                        $bool = true;
                        break;
                    }
                }
            }
        }

        if (!$bool && $rechargeLimitTemplateVideoData) {
            $videoData = $this->videosModel->getInfoById($params['video_id'], 'id, launch_start_time, created_at');

            $rechargeLimitTemplateData = $rechargeLimitTemplateVideoData['rechargeLimitTemplate'];

            $limitBool = false;
            if (!empty($rechargeLimitTemplateVideoData['recharge_limit_template_id'])) {

                if ($rechargeLimitTemplateData) {
                    $time = $videoData['launch_start_time'] ? $videoData['launch_start_time'] : $videoData['created_at'];
                    if ($time > time() - $rechargeLimitTemplateData['recharge_day'] * 86400) {
                        $limitBool = true;
                    }
                }

                if ($limitBool) {
                    // 收费起始集数限制
                    if ($params['sort'] > $rechargeLimitTemplateData['recharge_set']) {
                        return ['message' => Error::PAYMENT_START_COLLECTION_EXCEED . '第' . $rechargeLimitTemplateData['recharge_set'] . '集'];
                    }
                    $rechargedContent = json_decode($params['recharged_content'], true);
                    $notRechargedContent = json_decode($params['not_recharged_content'], true);
                    // 充值金额限制判断
                    if (!empty($rechargedContent) && is_array($rechargedContent)) {
                        foreach ($rechargedContent as $item) {
                            if ($item['recharge_price'] < $rechargeLimitTemplateData['recharge_amount']) {
                                return ['message' => Error::PAYMENT_AMOUNT_NOT_LESS_THAN_DESIGNATED_AMOUNT . '（' . $rechargeLimitTemplateData['recharge_amount'] . '）'];
                            }
                        }
                    }
                    if (!empty($notRechargedContent) && is_array($notRechargedContent)) {
                        foreach ($notRechargedContent as $item) {
                            if ($item['recharge_price'] < $rechargeLimitTemplateData['recharge_amount']) {
                                return ['message' => Error::PAYMENT_AMOUNT_NOT_LESS_THAN_DESIGNATED_AMOUNT . '（' . $rechargeLimitTemplateData['recharge_amount'] . '）'];
                            }
                        }
                    }
                }
            }
        }
        return $this->model->edit($params);
    }

    // 自定义充值模板列表
    public function customRechargeTemplateList($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $appletData = $this->officialAccountsModel->getInfoById($userInfo['cps_used_official_account_id'], 'applet_id');
        $appletId = $appletData['applet_id'];
        //添加一个状态判断
        $where = ['status' => 1];
        $cpsId = $userInfo['cps_user_id'];

        $responsibilityPerson = $this->responsibilityPersonModel->getInfoById($cpsId, 'id, is_distributor, is_branch_office_manage');
        if ($responsibilityPerson['is_distributor'] == 1) {
            // 分销商负责人
            $distributorPitcher = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPerson['id']], 'id');
            $pitcherIds = array_column($distributorPitcher, 'id');
            $where[]=['applet_id' , '=',$appletId];
            $where[] = ['responsibility_person_id', 'in', $pitcherIds];
        } elseif ($responsibilityPerson['is_branch_office_manage'] == 1) {
            // 分公司负责人
            $branchOfficePitcher = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPerson['id']], 'id');
            $pitcherIds = array_column($branchOfficePitcher, 'id');
            $where[] = ['responsibility_person_id', 'in', $pitcherIds];
        } elseif ($responsibilityPerson['id'] == config('enum.cps_user_id')) {
            // cps总帐号
        } else {
            // 投手
            $where[]=['applet_id', '=', $appletId];
            $where[] = ['responsibility_person_id', '=', $cpsId];
        }

        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }

        if (!empty($params['responsibility_person_id'])) {
            $where[] = ['responsibility_person_id', '=', $params['responsibility_person_id']];
        }
        $data = $this->model->getPagingDataByWhere($where, $page, $limit, 'id, name, type, responsibility_person_id, video_id, sort, charge_type, pay_amount, interval_recharge, recharged_content, not_recharged_content, created_at, updated_at', 'id desc');

        $responsibilityPersonIds = array_column($data['data'], 'responsibility_person_id');
        $responsibility = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'name, id');
        $pitcher = array_column($responsibility, 'name', 'id');

        $videoIds = array_column($data['data'], 'video_id');
        $videoData = $this->videosModel->getDataByIds($videoIds, 'name, id', 'id desc');
        $video = array_column($videoData, 'name', 'id');

        $ids = array_column($data['data'], 'id');
        $linkData = $this->linkModel->getDataByWhere(['is_new_recharge_setting' => 2, 'recharge_template_id' => $ids], 'recharge_template_id, id');
        $useLink = [];
        foreach ($linkData as $key => $value) {
            $useLink[$value['recharge_template_id']][] = $value['id'];
        }

        foreach ($data['data'] as $key => $value) {

            $data['data'][$key]['responsibility_person_name'] = !empty($pitcher[$value['responsibility_person_id']]) ? $pitcher[$value['responsibility_person_id']] : '';
            $data['data'][$key]['video_name'] = !empty($video[$value['video_id']]) ? $video[$value['video_id']] : '';
            $data['data'][$key]['use_link'] = !empty($useLink[$value['id']]) ? implode(',', $useLink[$value['id']]) : '';
            $data['data'][$key]['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
            $data['data'][$key]['updated_at'] = date('Y-m-d H:i:s', $value['updated_at']);
        }

        return $data;
    }

    // 自定义充值模板详情
    public function customRechargeTemplateDetail($params, $userInfo)
    {
        $data = $this->model->getInfoById($params['id'], 'id, name, type, video_id, sort, charge_type, pay_amount, interval_recharge, recharged_content, not_recharged_content');
        $data['interval_recharge'] = json_decode($data['interval_recharge'], true);
        $data['recharged_content'] = json_decode($data['recharged_content'], true);
        $data['not_recharged_content'] = json_decode($data['not_recharged_content'], true);
        $videoDetailData = $this->videoDetailsModel->getAllDataByVideoId($data['video_id'], 'id');
        $data['sylloge'] = count($videoDetailData);

        return $data;
    }

    // 获取自定义收费设置下拉列表
    public function getCustomRechargeTemplateSelect($params, $userInfo)
    {
        $appletData = $this->officialAccountsModel->getInfoById($userInfo['cps_used_official_account_id'], 'applet_id');
        $appletId = $appletData['applet_id'];
        $where = [
            ['video_id', '=', $params['video_id']]
        ];

        // 添加一个状态判断
        $where[] = ['status', '=', 1];

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } elseif ($userInfo['cps_user_id'] == config('enum.cps_user_id')) {
            // $where[] = [];
        } else {
            $where[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
            $where[]= ['applet_id', '=', $appletId];
        }

        $data = $this->model->getDataByWhere($where, 'id, name');

        return $data;
    }

    // 批量收费设置（新版本）
    public function batchRechargeSetting($params, $userInfo)
    {
        $linkIds = explode(',', $params['link_ids']);
        $linkData = $this->linkModel->getDataByWhere(['id' => $linkIds], 'id, video_id, is_new_recharge_setting, recharge_template_id');

        $saveData = [];
        $companyData = $this->responsibilityPersonModel->getInfoById($userInfo['cps_user_id'], 'company_id');
        $customRechargeData = $this->model->getInfoById($params['custom_recharge_id'], 'sort, recharged_content, not_recharged_content');

        foreach ($linkData as $key => $value) {
            if ($value['is_new_recharge_setting'] != 2) {
                return ['message' => Error::ONLY_NEW_VERSION_LINKS_CAN_BE_MODIFIED];
            }

            $rechargeLimitTemplateVideoData = $this->rechargeLimitTemplateVideoModel->selectWithTemplateFirstByVideoId(['recharge_limit_template_id'], $value['video_id']);

            $bool = false;
            if ($rechargeLimitTemplateVideoData) {
                $rechargeLimitTemplateId = $rechargeLimitTemplateVideoData['recharge_limit_template_id'];
                $rechargeLimitTemplateCompanyData = $this->rechargeLimitTemplateCompanyModel->getDataByWhere(['recharge_limit_template_id' => $rechargeLimitTemplateId], 'company_id');

                if ($rechargeLimitTemplateCompanyData) {
                    foreach ($rechargeLimitTemplateCompanyData as $val) {
                        if ($val['company_id'] == $companyData['company_id']) {
                            $bool = true;
                            break;
                        }
                    }
                }
            }

            if (!$bool && $rechargeLimitTemplateVideoData) {
                $videoData = $this->videosModel->getInfoById($value['video_id'], 'id, launch_start_time, created_at');

                $rechargeLimitTemplateData = $rechargeLimitTemplateVideoData['rechargeLimitTemplate'];

                $limitBool = false;
                if (!empty($rechargeLimitTemplateVideoData['recharge_limit_template_id'])) {

                    if ($rechargeLimitTemplateData) {
                        $time = $videoData['launch_start_time'] ? $videoData['launch_start_time'] : $videoData['created_at'];
                        if ($time > time() - $rechargeLimitTemplateData['recharge_day'] * 86400) {
                            $limitBool = true;
                        }
                    }

                    if ($limitBool) {
                        // 收费起始集数限制
                        if ($customRechargeData['sort'] > $rechargeLimitTemplateData['recharge_set']) {
                            return ['message' => Error::PAYMENT_START_COLLECTION_EXCEED . '第' . $rechargeLimitTemplateData['recharge_set'] . '集'];
                        }
                        $rechargedContent = json_decode($customRechargeData['recharged_content'], true);
                        $notRechargedContent = json_decode($customRechargeData['not_recharged_content'], true);
                        // 充值金额限制判断
                        if (!empty($rechargedContent) && is_array($rechargedContent)) {
                            foreach ($rechargedContent as $item) {
                                if ($item['recharge_price'] < $rechargeLimitTemplateData['recharge_amount']) {
                                    return ['message' => Error::PAYMENT_AMOUNT_NOT_LESS_THAN_DESIGNATED_AMOUNT . '（' . $rechargeLimitTemplateData['recharge_amount'] . '）'];
                                }
                            }
                        }
                        if (!empty($notRechargedContent) && is_array($notRechargedContent)) {
                            foreach ($notRechargedContent as $item) {
                                if ($item['recharge_price'] < $rechargeLimitTemplateData['recharge_amount']) {
                                    return ['message' => Error::PAYMENT_AMOUNT_NOT_LESS_THAN_DESIGNATED_AMOUNT . '（' . $rechargeLimitTemplateData['recharge_amount'] . '）'];
                                }
                            }
                        }
                    }
                }
            }

            $saveData[] = [
                'id' => $value['id'],
                'recharge_template_id' => $params['custom_recharge_id']
            ];
        }

        $num = $this->linkModel->saveAll($saveData);

        if (!$num) {
            return ['message' => Error::SETTING_FAIL];
        }
        return [];
    }
}
